<template>
  <view class="region-picker custom-comp">
    <picker mode="multiSelector" @change="onChange" @columnchange="onColumnchange" :range="range"
      :value="pickerIndexValue" range-key="name">
      <PickerValue style="height: 100%" :value-text="getShowValue" icon=""
        :placeholder="getPlaceholder" />
    </picker>
  </view>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { propTypes } from '@/utils/propTypes'
import PickerValue from '@/components/Form/components/PickerValue.vue'
import areaJsonData from './address.json'

interface AreaItem {
  area: string;
  areacode: string;
}

interface CityItem {
  city: string;
  citycode: string;
  areas: AreaItem[];
}

interface ProvinceItem {
  province: string;
  provincecode: string;
  citys: CityItem[];
}

// 定义地区数据结构类型
interface RegionItem {
  name: string;
  code: string;
}

// 声明 areaData 的类型
const areaData: ProvinceItem[] = areaJsonData as ProvinceItem[]

const props = defineProps({
  modelValue: {
    type: [String, Array],
    default: ''
  },
  placeholder: propTypes.string.def('请选择省市区')
})

const emits = defineEmits(['update:modelValue'])

// 选择器数据
const range = ref<any[][]>([[], [], []])
const pickerIndexValue = ref<number[]>([0, 0, 0])

// 显示值
const showVal = ref<any[]>([])

// 计算属性
const getShowValue = computed(() => {
  if (showVal.value.length === 0) return ''
  return showVal.value.map((v, index) => {
    if (index === 0) return v.province
    if (index === 1) return v.city
    return v.area
  }).join('')
})

const getPlaceholder = computed(() => props.placeholder)

// 初始化数据
const initPickerData = () => {
  // 转换数据格式
  const provinces = areaData.map(p => ({ name: p.province, ...p }))
  const defaultCitys = areaData[0]?.citys.map(c => ({ name: c.city, ...c })) || []
  const defaultAreas = areaData[0]?.citys[0]?.areas.map(a => ({ name: a.area, ...a })) || []
  
  range.value[0] = provinces
  range.value[1] = defaultCitys
  range.value[2] = defaultAreas
}

// 初始化时调用一次
initPickerData()

// 列变化处理
const onColumnchange = (e: { detail: { column: number; value: number } }) => {
  const { column, value } = e.detail
  
  if (column === 0) {
    // 省份改变，更新市和区
    const citys = areaData[value].citys.map(c => ({ name: c.city, ...c }))
    const areas = areaData[value].citys[0]?.areas.map(a => ({ name: a.area, ...a })) || []
    range.value[1] = citys
    range.value[2] = areas
    pickerIndexValue.value = [value, 0, 0]
  } else if (column === 1) {
    // 市改变，更新区
    const areas = areaData[pickerIndexValue.value[0]].citys[value].areas.map(a => ({ name: a.area, ...a })) || []
    range.value[2] = areas
    pickerIndexValue.value = [pickerIndexValue.value[0], value, 0]
  } else {
    pickerIndexValue.value = [pickerIndexValue.value[0], pickerIndexValue.value[1], value]
  }
}

// 选择完成
const onChange = (e: any) => {
  const indexs = e.detail.value as number[]
  if (indexs.length < 3) return; // 确保选择了省、市、区
  const province = range.value[0][indexs[0]]
  const city = range.value[1][indexs[1]]
  const area = range.value[2][indexs[2]]
  
  showVal.value = [province, city, area]

  // 更新返回的结构，确保包含所需的属性
  const result = [
    {
      name: province.province,
      code: province.provincecode
    },
    {
      name: city.city,
      code: city.citycode
    },
    {
      name: area.area,
      code: area.areacode
    }
  ]

  // 发出更新事件
  emits('update:modelValue', result)
}

// 修改 initSelectedValue 方法来适应新的数据格式
const initSelectedValue = () => {
  if (!props.modelValue) return
  
  // 如果是数组格式
  if (Array.isArray(props.modelValue) && props.modelValue.length === 3) {
    const provinceItem = props.modelValue[0] as RegionItem
    const cityItem = props.modelValue[1] as RegionItem
    const areaItem = props.modelValue[2] as RegionItem

    // 在全局数据源中查找匹配的省份索引
    const provinceIndex = areaData.findIndex(p => p.provincecode === provinceItem.code)
    if (provinceIndex === -1) return

    // 获取省份数据
    const provinceData = areaData[provinceIndex]
    
    // 在选中的省份中查找匹配的城市索引
    const cityIndex = provinceData.citys.findIndex(c => c.citycode === cityItem.code)
    if (cityIndex === -1) return

    // 获取城市数据
    const cityData = provinceData.citys[cityIndex]
    
    // 在选中的城市中查找匹配的区域索引
    const areaIndex = cityData.areas.findIndex(a => a.areacode === areaItem.code)
    if (areaIndex === -1) return

    // 更新选择器索引值
    pickerIndexValue.value = [provinceIndex, cityIndex, areaIndex]
    
    // 更新选择器数据
    range.value[1] = provinceData.citys.map(c => ({ name: c.city, ...c }))
    range.value[2] = cityData.areas.map(a => ({ name: a.area, ...a }))

    // 更新显示值
    showVal.value = [
      provinceData,
      cityData,
      cityData.areas[areaIndex]
    ]
    return
  }
  
  // 向后兼容旧的字符串格式
  if (typeof props.modelValue === 'string') {
    const parts = props.modelValue.split('-');
    if (parts.length !== 3) return; // 确保格式正确
    const [provinceInfo, cityInfo, areaInfo] = parts;
    const [provinceName, provinceCode] = provinceInfo.split('|')
    const [cityName, cityCode] = cityInfo.split('|')
    const [areaName, areaCode] = areaInfo.split('|')
    
    const provinceIndex = areaData.findIndex(p => p.provincecode === provinceCode)
    if (provinceIndex === -1) return

    const provinceData = areaData[provinceIndex]
    const cityIndex = provinceData.citys.findIndex(c => c.citycode === cityCode)
    if (cityIndex === -1) return

    const cityData = provinceData.citys[cityIndex]
    const areaIndex = cityData.areas.findIndex(a => a.areacode === areaCode)
    if (areaIndex === -1) return

    pickerIndexValue.value = [provinceIndex, cityIndex, areaIndex]
    
    // 更新选择器数据
    range.value[1] = provinceData.citys.map(c => ({ name: c.city, ...c }))
    range.value[2] = cityData.areas.map(a => ({ name: a.area, ...a }))

    showVal.value = [
      provinceData,
      cityData,
      cityData.areas[areaIndex]
    ]
  }
}

watch(() => props.modelValue, () => {
  initSelectedValue()
}, { immediate: true })

</script>

<style lang="scss" scoped>
@import '@/components/Form/styles/form.scss';

.region-picker {
  width: 100%;
  position: relative;
}
</style> 